package com.example.service1.call.controller;


import com.example.service1.common.api.Service1;
import com.example.service1.common.api.entity.ResponseResult;
import com.example.service1.common.dto.FileTestDto;
import com.example.service1.common.dto.TestDto;
import com.example.service1.common.vo.TestVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController("feignController")
@RequestMapping("/feign")
public class FeignController {

    /**
     * FeignClient假客户端
     */
    //由于idea编译器将其fallback认为是一个装配类，所以会爆红，虽然不会报错。为了不报红而添加了@Qualifier
    @Qualifier("com.example.service1.common.api.Service1")
    @Autowired
    private Service1 service1;


    /**
     * 服务发现客户端。可以获取服务中心上的服务信息
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/get/discoveryServices")
    public Map<String, List<ServiceInstance>> getServiceInstances(){
        if(Math.round(Math.random()*5)==1){
            throw new RuntimeException("异常");
        }
        Map<String, List<ServiceInstance>> servicesMap = new HashMap<>();
        List<String> serviceNames = discoveryClient.getServices();
        for(String name:serviceNames){
            List<ServiceInstance> instances = discoveryClient.getInstances(name);
            servicesMap.put(name,instances);
        }
        return servicesMap;
    }



    @GetMapping("/get/noArg")
    public ResponseResult<TestVo> feignNoArgGet(){
        return service1.noArgGet();
    }


    @GetMapping("/get/pathArg")
    public ResponseResult<TestVo> feignPathArgGet(){
        return service1.pathArgGet("pathArg",LocalDate.now());
    }

    @GetMapping("/post/pathAndBodyArg")
    public ResponseResult<TestVo> feignPathAndBodyArgPost(){
        return service1.pathAndBodyArgPost("pathArg", LocalDate.now(), TestDto.defaultCreate().setAge(1616L));
    }


    @GetMapping(value = "/put/pathAndBodyArg")
    public ResponseResult<TestVo> feignPathAndBodyArgPut(){
        return service1.pathAndBodyArgPut("pathArg", LocalDate.now(), TestDto.defaultCreate().setAge(1616L));
    }

    /**
     * 不支持文件上传
     */
    @PostMapping("/post/file")
    public ResponseResult<TestVo> pathAndBodyArgAndFileArgPost(FileTestDto fileTestDto){
            return service1.pathAndBodyArgAndFileArgPost("元素e",fileTestDto);
    }

}
